﻿namespace SharpF2.Components
{
	using System.Collections;
	using System.Collections.Generic;
	using System.Collections.ObjectModel;
	using System.Collections.Specialized;
	using System.Linq;
	using System.Windows;
	using System.Windows.Controls;

	/// <summary>
	/// Interaction logic for ListViewExtended.SelectedItems
	/// </summary>
	public partial class ListViewExtended<ItemType>
	{
		#region Public Attributes

		public static readonly DependencyProperty SelectedItemsSourceProperty =
			DependencyProperty.Register("SelectedItemsSource",
			                            typeof (IEnumerable<ItemType>),
			                            typeof (ListViewExtended<ItemType>),
			                            new PropertyMetadata(
			                            	new PropertyChangedCallback(
			                            		(s, e) =>
			                            			{
			                            				var listViewExtended = s as ListViewExtended<ItemType>;
			                            				if (null == listViewExtended) return;

			                            				var newSource = e.NewValue as INotifyCollectionChanged;
			                            				if (null != newSource)
			                            					newSource.CollectionChanged += listViewExtended.OnSelectedItemsSourceChanged;

			                            				var newCollection = e.NewValue as IEnumerable;
			                            				if (null != newCollection)
			                            					listViewExtended.UpdateSelectedItems(newCollection);
			                            			}
			                            		)));

		#endregion

		#region Public Properties

		public IEnumerable<ItemType> SelectedItemsSource
		{
			get { return GetValue(SelectedItemsSourceProperty) as IEnumerable<ItemType>; }
			set { SetValue(SelectedItemsSourceProperty, value); }
		}

		#endregion

		#region Private Members

		private void OnSelectedItemsSourceChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			UpdateSelectedItems(sender as IEnumerable);
		}

		private void UpdateSelectedItems(IEnumerable collection)
		{
			SetSelectedItems(collection);
		}

		#endregion

		#region Protected Members

		protected override void OnSelectionChanged(SelectionChangedEventArgs e)
		{
			base.OnSelectionChanged(e);

			if (null == SelectedItemsSource) return;

			SelectedItemsSource = new ObservableCollection<ItemType>(SelectedItems.Cast<ItemType>());
		}

		#endregion
	}
}